package com.ym.excel.jfree;

import org.jfree.chart.*;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;

import java.text.DecimalFormat;

/**
 * @Author: smuswc
 * @Date: 2018/2/7 13:15
 * @Description:
 */
public class YMJFreeLineChart extends YMBaseChart {

    YMJFreeLineChart() {}


    /**
     *  JFreeChart jFreeChart = ChartFactory.createLineChart("柱形图","水果", "数量", getDataSet(), PlotOrientation.VERTICAL, true, false,false);
     * @param jFreeChart
     * @param path 图片存储路径
     * @return 返回生成图片路径
     * @throws Exception
     */

    public String drawChart(JFreeChart jFreeChart, String path, Integer width, Integer height) throws Exception {
        // 图片路径
        path = getImagePath(path);

        LineAndShapeRenderer barRenderer = (LineAndShapeRenderer) jFreeChart.getCategoryPlot().getRenderer();
        // 设置显示数值
        barRenderer.setItemLabelAnchorOffset(5f);
        barRenderer.setDefaultItemLabelGenerator(new StandardCategoryItemLabelGenerator("{2}", new DecimalFormat()));
        barRenderer.setDefaultShapesFilled(true);
        barRenderer.setDefaultShapesVisible(true);
        barRenderer.setDefaultItemLabelsVisible(true);
        drawAxialChart(jFreeChart, path, width, height);
        return path;
    }

    /**
     * @param jFreeChart
     * @param path
     * @param width
     * @param height
     * @return
     */
    protected void drawAxialChart(JFreeChart jFreeChart, String path, Integer width, Integer height) throws Exception{
        jFreeChart.setBackgroundPaint(java.awt.Color.WHITE);
        CategoryPlot categoryPlot = jFreeChart.getCategoryPlot();

        CategoryAxis categoryAxis = categoryPlot.getDomainAxis();
        categoryAxis.setTickLabelFont(new java.awt.Font("sans-serif", java.awt.Font.PLAIN, 11));
        categoryAxis.setLabelFont(new java.awt.Font("宋体", java.awt.Font.PLAIN, 12));
        categoryAxis.setAxisLineVisible(false);

        NumberAxis numberAxis = (NumberAxis) categoryPlot.getRangeAxis();
        numberAxis.setTickLabelFont(new java.awt.Font("sans-serif", java.awt.Font.PLAIN, 12));
        numberAxis.setLabelFont(new java.awt.Font("黑体", java.awt.Font.PLAIN, 12));
        // 设置纵轴方向的最大与最小距离
        numberAxis.setUpperMargin(0.15);
        numberAxis.setLowerMargin(0.15);
        // 图例信息
        jFreeChart.getLegend().setItemFont(new java.awt.Font("宋体", java.awt.Font.PLAIN, 12));
        categoryPlot.setDomainAxis(categoryAxis);
        jFreeChart.setAntiAlias(true);

        // 生成图片
        generateImage(jFreeChart, path, width, height);
    }

}
